import re

from database import *



class CreateTable:

    @staticmethod
    def database_exists(cursor, db_name):
        sql = "show databases;"
        dbs = cursor.query(sql)
        if db_name in [db.get('Database') for db in dbs]:
            return True
        else:
            return False

    @staticmethod
    def table_exists(cursor, table_name):  # 这个函数用来判断表是否存在
        sql = "show tables;"
        tables = cursor.query(sql)
        table_list = re.findall('(\'.*?\')', str(tables))
        table_list = [re.sub("'", '', each) for each in table_list]
        if table_name in table_list:
            return True  # 存在
        else:
            return False  # 不存在

    @staticmethod
    def create_database(cursor):
        database_name = mysql_config.get('database')
        if not CreateTable.database_exists(cursor, database_name):
            sql = """CREATE DATABASE IF NOT EXISTS krpool DEFAULT CHARSET utf8 COLLATE utf8_general_ci;"""
            cursor.execute(sql)
        init_sql_db()

    @staticmethod
    def create_proxies(cursor):
        """
        创建MySQL表结构
        :param cursor:
        :return:
        """
        table_name = 'proxies'
        if not CreateTable.table_exists(cursor, table_name):
            sql = f"""
            CREATE TABLE `{table_name}` (
             `id` INT NOT NULL AUTO_INCREMENT COMMENT '代理id',
             `proxy` VARCHAR ( 100 ) NOT NULL DEFAULT '0' COMMENT '代理',
             `source` VARCHAR ( 100 ) NOT NULL DEFAULT '0' COMMENT '代理来源（哪个网站）',
             `status` TINYINT NOT NULL DEFAULT '0' COMMENT '是否可用（1：可用，0：不可用）',
             `create_time` INT NOT NULL DEFAULT '0' COMMENT '创建时间',
             `update_time` INT NOT NULL DEFAULT '0' COMMENT '修改时间',
             `fail_time` INT NOT NULL DEFAULT '0' COMMENT '代理失效时间',
             `is_deleted` TINYINT NOT NULL DEFAULT '0' COMMENT '是否已删除',
             PRIMARY KEY ( `id` ),
             KEY `idx_proxy` ( `proxy` )
            ) ENGINE = INNODB DEFAULT CHARSET = utf8 COMMENT = '代理';
            """
            cursor.execute(sql)


def create_table():
    CreateTable.create_database(init_db)
    sql_db = get_sql_db()
    CreateTable.create_proxies(sql_db)


create_table()
